package com.shjn.squirrel.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.shjn.squirrel.R;
import com.shjn.squirrel.application.MyApplication;
import com.shjn.squirrel.bean.httpBean.GetImageReq;
import com.shjn.squirrel.bean.httpBean.RespCommonResult;
import com.shjn.squirrel.model.Constant;
import com.shjn.squirrel.model.LocalStorage;
import com.shjn.squirrel.utils.OkhttpHelper;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 首页底部轮播图
 */
public class BottomFragment extends BaseFragment {

    private static BottomFragment instance;
    private Banner mBanner;
    private ArrayList<Object> mImages;

    public BottomFragment() {
    }

    public synchronized static BottomFragment getInstance() {
        if (instance == null) {
            instance = new BottomFragment();
        }
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return createView(inflater, R.layout.bottom, container);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    /**
     * 初始化相关控件
     */
    private void initView() {
        //初始化轮播图控件
        mBanner = (Banner) mView.findViewById(R.id.banner);
        mBanner.setDelayTime(30000);
        mBanner.setBannerStyle(BannerConfig.NOT_INDICATOR);
        mImages = new ArrayList();
        //默认轮播图
        mImages.add(R.drawable.banner1);
        mImages.add(R.drawable.banner2);
        mImages.add(R.drawable.banner3);
        //设置图片集合
        mBanner.setImages(mImages);
        //设置图片加载器
        mBanner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                //Glide 加载图片简单用法
                Glide.with(context).load(path).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).placeholder(R.drawable.banner1).into(imageView);
            }
        });
        //banner设置方法全部调用完毕时最后调用
        mBanner.start();


        //如果出厂设置了，从服务器获取首页轮播图(Constant.baseUrl + "machine/home/images")
        if (!LocalStorage.getDeviceID(MyApplication.getInstance()).isEmpty()) {
            OkhttpHelper.postRequest(Constant.myBaseUrl + "squirrelWebDemo/pictureServlet",
                    new Gson().toJson(new GetImageReq(LocalStorage.getDeviceID(MyApplication.getInstance()), 1)),
                    new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.i("info", "homeImages_onFailure: " + e.getMessage());
                        }

                        @Override
                        public void onResponse(Call call, Response response) {
                            try {
                                RespCommonResult result = new Gson().fromJson(response.body().string(), RespCommonResult.class);
                                if (result.getStateCode() == 1) {
                                    ArrayList<String> pictures = (ArrayList<String>) result.getResult().get("picture");
                                    mImages = new ArrayList();
                                    for (String pictureUrl : pictures) {
                                        mImages.add(pictureUrl);
                                    }
                                    //更新轮播图
                                    mActivity.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (mBanner != null && BottomFragment.getInstance().isAdded()) {
                                                mBanner.update(mImages);
                                            }
                                        }
                                    });
                                }
                            } catch (IOException e) {
                                Log.i("info", "homeImages_onFailure: " + e.getMessage());
                            }
                        }
                    });
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mBanner != null) {
            mBanner.releaseBanner();
            mBanner = null;
        }
        if (mImages != null) {
            mImages.clear();
            mImages = null;
        }
    }
}
